#!/bin/python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    By :陈狍子 e4ting@qq.com 2024-12-07 22:44:49
"""
import sys,os
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack

import multiprocessing

from e4ting import util,log

from app.flaskapp  import app_context
from models.mysqls import db,ModelRoom

from .room        import Room
from .cash        import Utxo,VirtualAccount

def create_robots():
    names = ["嘉靖", "严嵩", "徐阶", "海瑞", "张居正", "何茂才"]
    for i,name in enumerate(names):
        who = VirtualAccount(uid=f"robot{i}")
        who.init()
        who.create_record(name=name)
        who.init_cash()

@app_context()
def start_room(name="", bank=None, dealer=None, judge=None, status="", **kwargs):
    log.info(f"{name} 启动")
    room_id = kwargs["id"]
    room = Room(room_id)
    room.build_cache()
    room.init()
    room.run()
    return True

def room_process(room_info):
    pid = os.getpid()
    log.info(f"进程ID：{pid}")
    return start_room(**room_info)

@app_context()
def main(op):
    # create_robots()
    # return
    # who = VirtualAccount(uid="E400000000")
    # to  = VirtualAccount(uid="E400000001")

    # who.init()
    # to.init()

    # who.create_record("嘉靖")
    # to.create_record("严嵩")

    # utxo = Utxo(VirtualAccount.get_bank(), who)
    # utxo.do_withdraw(10, "小盲下注")

    # utxo = Utxo(VirtualAccount.get_bank(), to)
    # utxo.do_withdraw(10, "小盲下注")

    # room = Room(op.room)
    # # room.create_record(name="内阁", detail="神仙斗法之地")
    # room.init()
    # room.run()

    rooms = [item.to_json() for item in db.session.query(ModelRoom).all() ]
    util.printf(rooms)
    with multiprocessing.Pool(processes=len(rooms)) as pool:
        # 提交任务
        results = pool.map(room_process, rooms)

def argv_parse():
    import argparse
    parser = argparse.ArgumentParser(
        prog=sys.argv[0],
        description="游戏主导入口"
    )
    parser.add_argument(
        '-d', '--debug',
        action='store_true',
        default=False,
        help='调试模式'
    )
    parser.add_argument(
        '-r', '--room',
        action='store',
        type=int,
        default=4,
        help='房间id'
    )
    return parser.parse_args()

if __name__ == '__main__':
    main(argv_parse())
